<template>
  <div class="admin-page">
    <div class="page-header">
      <h1>应用管理</h1>
      <p class="page-description">管理所有应用的信息和状态</p>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="应用名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入应用名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="创建者">
          <el-input
            v-model="searchForm.creator"
            placeholder="请输入创建者"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="正常" value="normal" />
            <el-option label="精选" value="featured" />
            <el-option label="已部署" value="deployed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchApps">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 应用列表 -->
    <div class="table-section">
      <el-table
        :data="appList"
        v-loading="loading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column prop="name" label="应用名称" min-width="150">
          <template #default="{ row }">
            <div class="app-name-cell">
              <span class="app-name">{{ row.name }}</span>
              <el-tag v-if="row.priority === 99" type="warning" size="small">
                精选
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="creator" label="创建者" width="120" />
        
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              @click="viewApp(row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="editApp(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.priority !== 99"
              size="small"
              type="warning"
              @click="setFeatured(row)"
            >
              精选
            </el-button>
            <el-button
              v-else
              size="small"
              @click="unsetFeatured(row)"
            >
              取消精选
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteApp(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedApps.length > 0">
      <el-card>
        <div class="batch-info">
          <span>已选择 {{ selectedApps.length }} 个应用</span>
          <div class="batch-buttons">
            <el-button
              type="warning"
              @click="batchSetFeatured"
            >
              批量精选
            </el-button>
            <el-button
              type="danger"
              @click="batchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 应用详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="应用详情"
      width="600px"
    >
      <div v-if="currentApp" class="app-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="应用ID">{{ currentApp.id }}</el-descriptions-item>
          <el-descriptions-item label="应用名称">{{ currentApp.name }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ currentApp.creator }}</el-descriptions-item>
          <el-descriptions-item label="优先级">{{ currentApp.priority }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" span="2">
            {{ formatDateTime(currentApp.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" span="2">
            {{ formatDateTime(currentApp.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="应用描述" span="2">
            {{ currentApp.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="app-actions" style="margin-top: 20px;">
          <el-button type="primary" @click="editApp(currentApp)">
            编辑应用
          </el-button>
          <el-button @click="goToChat(currentApp)">
            进入对话
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { appApi } from '@/api'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  name: '',
  creator: '',
  status: ''
})

// 应用列表
const appList = ref([])
const loading = ref(false)
const selectedApps = ref([])

// 分页
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 对话框
const detailDialogVisible = ref(false)
const currentApp = ref(null)

// 初始化
onMounted(() => {
  loadApps()
})

// 加载应用列表
const loadApps = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await appApi.getAppPageAdmin(params)
    if (response.code === 0) {
      appList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载应用列表失败')
    }
  } catch (error) {
    console.error('加载应用列表失败:', error)
    ElMessage.error('加载应用列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索应用
const searchApps = () => {
  pagination.current = 1
  loadApps()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    creator: '',
    status: ''
  })
  pagination.current = 1
  loadApps()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadApps()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadApps()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedApps.value = selection
}

// 查看应用
const viewApp = (app) => {
  currentApp.value = app
  detailDialogVisible.value = true
}

// 编辑应用
const editApp = (app) => {
  router.push({
    name: 'EditApp',
    params: { id: app.id }
  })
}

// 进入对话
const goToChat = (app) => {
  router.push({
    name: 'ChatPage',
    params: { id: app.id }
  })
}

// 设置精选
const setFeatured = async (app) => {
  try {
    await ElMessageBox.confirm(
      `确定要将应用「${app.name}」设置为精选吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await appApi.updateApp(app.id, {
      ...app,
      priority: 99
    })
    
    if (response.code === 0) {
      ElMessage.success('设置精选成功')
      loadApps()
    } else {
      ElMessage.error(response.message || '设置精选失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('设置精选失败:', error)
      ElMessage.error('设置精选失败')
    }
  }
}

// 取消精选
const unsetFeatured = async (app) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消应用「${app.name}」的精选状态吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await appApi.updateApp(app.id, {
      ...app,
      priority: 0
    })
    
    if (response.code === 0) {
      ElMessage.success('取消精选成功')
      loadApps()
    } else {
      ElMessage.error(response.message || '取消精选失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消精选失败:', error)
      ElMessage.error('取消精选失败')
    }
  }
}

// 删除应用
const deleteApp = async (app) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除应用「${app.name}」吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const response = await appApi.deleteApp(app.id)
    
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadApps()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量设置精选
const batchSetFeatured = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedApps.value.length} 个应用设置为精选吗？`,
      '确认批量操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const promises = selectedApps.value.map(app => 
      appApi.updateApp(app.id, { ...app, priority: 99 })
    )
    
    await Promise.all(promises)
    ElMessage.success('批量设置精选成功')
    loadApps()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量设置精选失败:', error)
      ElMessage.error('批量设置精选失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedApps.value.length} 个应用吗？此操作不可恢复！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const promises = selectedApps.value.map(app => appApi.deleteApp(app.id))
    await Promise.all(promises)
    
    ElMessage.success('批量删除成功')
    loadApps()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    normal: '',
    featured: 'warning',
    deployed: 'success'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    normal: '正常',
    featured: '精选',
    deployed: '已部署'
  }
  return statusMap[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.admin-page {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.app-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.app-name {
  font-weight: 500;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.batch-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

.app-detail {
  padding: 0;
}

.app-actions {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-page {
    padding: 16px;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .batch-actions {
    left: 16px;
    right: 16px;
    transform: none;
  }
}
</style>